<?php
class MemberAction extends CommonAction {
	function index(){
		$this->dao->checkEmpty();//number 会员编号测空并补充
        $myid=D('User')->where(' id = '.session(C('USER_AUTH_KEY')))->getField('member_id');
		if(!isset($_GET['level'])){
			$this->level='9999';
		}
        if($myid>0){
            $mymap='mm.member_id = '.$myid;
            if($this->_get('keywords')){
                $mymap.= " and (m.nickname like '%".$this->_get('keywords')."%' or m.id = '".$this->_get('keywords')."')";
                $this->keywords = $this->_get('keywords');
            }
            if(isset($_GET['level'])){
                if($this->_get('level') != '9999'){
                    $mymap .= " and ( mm.level = '".$this->_get('level')."')";
                }
                $this->level = $this->_get('level');
            }
            $this->initView();
            D('Member_member')->_list($this->view,$mymap);
        }else{
            $this->listmap="1";
            if($this->_get('keywords')){
                $this->listmap .= " and (nickname like '%".$this->_get('keywords')."%' or id like '%".$this->_get('keywords')."%' or number like '%".$this->_get('keywords')."%')";
                $this->keywords = $this->_get('keywords');
            }
            if(isset($_GET['level'])){
                if($this->_get('level') != '9999'){
                    $this->listmap .= " and (level = '".$this->_get('level')."')";
                }
                $this->level = $this->_get('level');
            }
            $this->listmap.=" and site_id=".$this->siteid. '  ';//and pid = 0
            parent::_list();
            $map['site_id'] = $this->siteid;
            $coupons = M('coupon')->where($map)->select();
            $this->assign("coupons",$coupons);
        }
		$this->myid=$myid;
        $this->getLevelNameList = $this->dao -> getLevelNameList();
		$this->display();
	}
    public function sendCoupon(){
		$coupon_id = $this->_post('coupon_id');
		$this->ids = explode(',', $this->_post('ids'));
		$need = count($this->ids);
		import("@.ORG.Coupon.Coupon");
        $Coupon = new Coupon($coupon_id,"0");
        if($Coupon->canUse()){
        	$exist = $Coupon->exist();
        	if($need <= $exist){
        		$ret['status'] = 1;
        		$ret['info'] = null;
        		foreach($this->ids as $openid){
        			$member_map['openid'] = $openid;
        			$member_map['site_id'] = $this->siteid;
        			$member = M('member')->where($member_map)->find();
        			if($member && $result = $Coupon->getCoupon($member['id'])){
        				$msg = "赠送您一张".$Coupon->coupon['title']."优惠券，价值".
        				$Coupon->coupon['discount']."元，在商城买满".$Coupon->coupon['full']."可以使用，有效期为".
        				$Coupon->coupon['sn_expires']."天";
        				sendWXMsg($openid,$msg);
        			}else{
        				$ret['status'] = 0;
        				$ret['info'] .= "赠送用户ID为".$openid."优惠券时发生错误，赠送该用户失败<br>";
        			}
        		}
        		$ret['info'] = $ret['info'] ? $ret['info'] : "发放成功";
        	}else{
        		$ret['status'] = 0;
        		$ret['info'] = "发放数量超出优惠券数量";
        	}
        }
        echo json_encode($ret);

	    //显示发送页面
		// if($this->_post('ids')){
		// 	$this->ids = explode(',', $this->_post('ids'));
		// 	$count = 0;
		// 	foreach($this->ids as $v){
		// 		if(sendWXMsg($v, $this->_post('msg'))){
		// 			$count ++;
		// 		}
		// 	}
		// 	$ret['status'] = 1;
		// 	$ret['info'] = $count;
		// 	$ret['data'] = '';
		// 	echo json_encode($ret);
		// }
	}
	
	//查看下级会员
	 function sindex(){
		$this->id = $this->_get('id');
		$this->getLevelNameList = $this->dao -> getLevelNameList();
//		if($this->_get('keywords')){
//			$map .= " and (m.nickname like '%".$this->_get('keywords')."%' or m.id = '".$this->_get('keywords')."')";
//			$this->keywords = $this->_get('keywords');
//		}
		if($this->_get('deep')){
			$deep=$this->_get('deep');
			$this->deep = $this->_get('deep');
		}
         $this->initView();
         $pagesize= 10;
         if($_REQUEST['pagesize']){
             $pagesize = $_REQUEST['pagesize'];
         }
         D('Member')->getChildrens($this->view,$this->id,$deep,$pagesize);
        $this->display();
	}
	//编辑会员
	public function edit(){
		//$this->group_list=M('Member_group')->where(array('site_id'=>$this->siteid))->select();
		$this->getLevelNameList = $this->dao -> getLevelNameList();
		//$this->role_list=M('Member_group')->alias('r')->join('left join __MEMBER_ROLE_USER__ ru ON r.id=ru.role_id and ru.user_id='.$this->_get('id')) -> where(array('r.user_id' => $_SESSION[C('USER_AUTH_KEY')])) -> select();
        $this->role_list=D('Member_group')-> getList2(0,0,array('site_id'=>$this->siteid));
		$this->supplierList=M('Supplier')->alias('s')->join('left join __MEMBER_SUPPLIER__ ms ON s.id=ms.supplier_id and ms.member_id='.$this->_get('id')) -> where(array('s.site_id' => $this->siteid)) -> Field('s.*,ms.member_id,ms.supplier_id') -> select();
		parent::edit();
	}
	//更新用户信息
	public function update(){
		$memberInfo=session('memberInfo');
		if($_POST['level']!=$memberInfo){
		$_POST['uplevel_time']=time();	
		}
		$member_id = $this->_post('id');
		if($this -> _post('leveldown') == 0){
			M('Member_member') -> where(array('smember_id' => $member_id)) -> data(array('level' => $this->_post('level'))) -> save();
			
		}
        $_POST['group_id']=$_POST['role_id'][0];
		if($_POST['password']!=''){
			$_POST['password']=md5($_POST['password']);
			$user=D('User')->where('member_id = '.$member_id)->getfield('id');
			if($user){
				D('User')->where('id = '.$user)->save(array('password'=>$_POST['password']));
			}
		}
		if($member_id){
			$data1=$_POST;
			//dump($data);exit(); 
			$role_user=M('Member_role_user');
            $role_user->where(array('user_id'=>$data1['id']))->delete();
			foreach($data1['role_id'] as $k=>$v){
				$r['user_id']=$data1['id'];
				$r['role_id']=$v;
                if(!$role_user->add($r)){
					$flag=false;
				}
			}
			$db = M('Member_supplier');
			$db -> where(array('member_id' => $member_id, 'site_id' => $this->siteid)) -> delete();
			//重新写入
			foreach($_POST['supplier_id'] as $k => $v){
				$data['supplier_id'] = $v;
				$data['member_id'] = $member_id;
				$data['site_id'] = $this->siteid;
				$db -> add($data);
				
				M('Supplier')->where('id = '.$v)->save($data);
			}
		}
		parent::update();
	}
	public function sendMsg(){
	    //显示发送页面
		if($this->_post('ids')){
			$this->ids = explode(',', $this->_post('ids'));
			$count = 0;
			foreach($this->ids as $v){
				if(sendWXMsg($v, $this->_post('msg'))){
					$count ++;
				}
			}
			$ret['status'] = 1;
			$ret['info'] = $count;
			$ret['data'] = '';
			echo json_encode($ret);
		}
	}
	//更新父ID
	public function updatePid(){
		if($this->_post('pid')){
			$pid = $this->_post('pid');
			$member_id = $this -> _post('member_id');
			$ret = $this->dao -> updatePid($member_id, $pid);
			if($ret){
				$this->success('操作成功！');
			}else{
				$this->error('操作失败，该会员的父ID不能更改');
			}
		}else{
			$this->error('参数错误');
		}
	}
	//更新父ID
	public function deletePid(){
		if($this->_get('pid')){
			$pid = $this->_get('pid'); 
			$member_id = $this -> _get('member_id');
			$ret = $this->dao -> deletePid($member_id, $pid);
			if($ret){
				$this->success('操作成功！');
			}else{
				$this->error('操作失败，该会员的父ID不能更改');
			}
		}else{
			$this->error('参数错误');
		}
	}
	
	public function delete(){
		//$this->error('您不能删除会员数据，这样会导致数据不完整！');exit;
		if(isset($_GET['id']) && intval($_GET['id'])>0){
			M('Member_member') -> where(array('site_id' => $this->siteid, 'smember_id' => $this->_get('id') )) -> delete();
			M('Member_member') -> where(array('site_id' => $this->siteid, 'member_id' => $this->_get('id') )) -> delete();
		}
		parent::delete();
		
	}
	
	//添加会员积分
	public function addintegral(){
		$id = $this->_get('id');

		if(IS_POST){
		   $id = $this->_post('id');
		   $integral = $this->_post('integral');
		   import("@.ORG.Integrals.Integral");
		   $Integral = new Integral($id);
		   $mes = $Integral->giveIntegral($integral);
		   if($mes){
				$this->success('操作成功！');
				exit;
			}else{
				$this->error('操作失败');
				exit;
			}
		}
		
		$this->assign('id',$id);
		$this->display();
	}
	
	//会员直接登录
	public function login(){
		$member = $this->dao -> where(array('site_id' => $this->siteid, 'id' => $this-> _get('id'))) -> find();dump($member);
		session('memberInfo', $member);
		redirect('/'.$this->siteid.U('Member/Index/index'));
	}
	public function show(){
		if($_GET['member_id']){
			$member_id=$_GET['member_id'];
		}else{
			$member_id=D('User')->where(' id = '.session(C('USER_AUTH_KEY')))->getField('member_id');
		}
	    $this->listmap='site_id ='.__SITEID__.' and id != '.$member_id;
	    if(isset($_GET['keywords'])){
            $this->listmap .= " and (nickname like '%".$this->_get('keywords')."%' or id = '".$this->_get('keywords')."')";
            $this->keywords = $this->_get('keywords');
        }
        $connected=D('Member_connect')->getField('referee_id',true);
	    $connected=implode(',',array_flip(array_flip($connected)));
	    if($connected){
	        $this->listmap.=' and id not in ('.$connected.')';
        }else{
        }
        $list=D('Member')->where($this->listmap)->select();
        import ( 'ORG.Util.Page' );
        $p=new Page(count($list), 6);
        $list = D('Member')->where($this->listmap)->limit($p->firstRow.','.$p->listRows) -> select();
        $this->pages = $p -> show();
        $this->list = $list;
	    $this->display();
    }
    //用户关联供货商
    public function connect(){
        if($_GET['member_id']&&$_GET['referee_id']){
            $data['member_id']=$_GET['member_id'];
            $data['referee_id']=$_GET['referee_id'];
            //member 关联 referee,记录referee的level 为type
            $data['type']=D('Member')->where('id ='.$data['referee_id'])->getfield('level');
            $res=$this->dao->connect($data);
            if($res){
                $this->success('操作成功',U('Member/show',['member_id'=>$data['member_id']]));
            } else {
                $this->error($res);
            }
        }
    }
    public function changeLevel(){
        $data['id']=$_POST['id'];
        $data['level']=$_POST['level'];
		$data['uplevel_time']=time();
        $re=$this->dao->changeLevel($data);
        echo json_encode($re);
    }
    public function mybelong(){
		$this->getLevelNameList = $this->dao -> getLevelNameList();
        $this->display();
    }
    public function belong(){
        if($_GET['member_id']){
			if($_GET['level']=='all'){
				$map = '1 and ';
			}else{
				$map = 'level = '.$_GET['level'].' and ';
			}
			if($_GET['keywords']!=''){
				$map .="( nickname like '%".$_GET['keywords']."%' or name like '%".$_GET['keywords']."%' or id = '".$_GET['keywords']."') and ";
			}else{
				$map .='';
			}
            $myid=$_REQUEST['member_id'];
            $uper=D('Member_connect')->where('member_id = '.$myid)->getfield('referee_id',true);
            $uper=implode(',',array_flip(array_flip($uper)));
            if($uper){
				import ( 'ORG.Util.Page' );
                $all=D('Member')->where($map.' id in ('.$uper.')')->select();
				$p=new Page(count($all), 5);
				$info=D('Member')->where($map.' id in ('.$uper.')')->limit($p->firstRow.',
'.$p->listRows) ->select();
				foreach($info as $k => $v){
					$info[$k]['type']=$this->getLevel($v['level']);
				}
				$this->pages = $p -> show();
            }
			$idlist=array();
			array_push($idlist,$_GET['member_id']);
            $this->linkhtml=$this->mylink($idlist,$_GET['top_id']);
            $this->assign('info',$info);
            $this->display();
        }
    }

	public function mylink($id,$topid){
		$thisid=$id[0];
		if($thisid!=$topid){
			$mybottom=D('Member_connect')->where('referee_id = '.$thisid)->getField('member_id');
			if($mybottom!=$topid){
				array_unshift($id,$mybottom);
				return $this->mylink($id,$topid);
			}
			array_unshift($id,$mybottom);
			foreach($id as $k =>$v){
				$name=D('Member')->where('id = '.$v)->getField('nickname');
				$linkhtml.='<a onclick="showBelong('.$v.')" class="btn btn-info" style="margin-right:10px;margin-bottom:5px">'.$name.'</a>';
			}
		}else{
			$name=D('Member')->where('id = '.$thisid)->getField('nickname');
			$linkhtml.='<a onclick="showBelong('.$thisid.')" class="btn btn-info" style="margin-right:10px;margin-bottom:5px">'.$name.'</a>';
		}
		return $linkhtml;
	}
	public function getLevel($id){
		$site_id = defined('__ADMINSITEID__')?__ADMINSITEID__:__RELATEID__;
		$v = M('Affiliatesetting') -> where(array('site_id' => $site_id, 'status' => 1)) -> getfield('value');
		return unserialize($v)['levelname'][$id];
	}
	public function deleteconnect(){
	    $re=D('Member_connect')->deleteconnect($_GET['member_id'],$_GET['referee_id']);
        $r=D('Member_member')->where('member_id = '.$_GET['member_id'].' and smember_id = '.$_GET['referee_id'])->delete();
	    if($re||$r){
	        $this->success('取消关联成功');
        }else{
	        $this->error('取消关联失败');
        }
    }
    public function add(){
        $this->getLevelNameList = $this->dao -> getLevelNameList();
        $this->role_list=D('Member_group')-> getList2(0,0,array('site_id'=>$this->siteid));
        $this->display();
    }

	public function insert(){
		$_POST['uplevel_time']=time();
		$data=$_POST;
		$data['password']=md5($data['password']);
		$num=D('Member')->getMaxNumber($data['level']);
		$data['number']=D('Member')->fitNumber($data['level'],$num);
		if($jumpUrl == ''){
			$jumpUrl = (session('jumpUrl')&&session('jumpUrl')!='') ? session('jumpUrl') : U('Admin/' . MODULE_NAME . '/index');
		}
		if ($this->dao->create($data)) {
			$result = $this->dao->add();
			if (false !== $result) {
				$data['member_id']=$result;
				unset($data['id']);
				$data['account']=$data['username'];
				unset($data['username']);
				if($data['remark']=='')$data['remark']='  ';
				if($data['email']=='')$data['email']='  ';
				if($data['password']){
					$data['password']=$data['password'];
				}else{
					$data['password']=md5('123456');
				}
				$data['status']=1;
				$data['pid']=0;
				$adduser=D('User')->add($data);
				if($adduser){
					if($data['level']==6){//服务商6
						$roleid=4;
					}elseif($data['level']==5){//业务员5
						$roleid=5;
					}elseif($data['level']==2||$data['level']==3||$data['level']==4){//代理2-4
						$roleid=4;
					}elseif($data['level']==0){//消费者0
						$roleid=8;
					}elseif($data['level']==1){//商家1
						$roleid=1;
					}
					if(D('Role_user')->where('user_id = '.$adduser)->find()){
						D('Role_user')->where('user_id = '.$adduser)->data(['role_id'=>$roleid])->save();
					}else{
						D('Role_user')->data(['role_id'=>$roleid,'user_id'=>$adduser])->add();
					}
					$this->success('操作成功', $jumpUrl);
				}else{
					$this->error($this->dao->getError());
				}
			} else {
				$this->error($this->dao->getError());
			}
		} else {
			$this->error($this->dao->getError());
		}
	}

    public function test(){
        $re=$this->dao->checkEmpty();
    }
}